package org.laizili.solution.leetcode;

import java.util.Arrays;

/**
 * <a href="https://leetcode.cn/problems/diagonal-traverse/">498. 对角线遍历</a>
 */
public class Problem498 {
    private static class Solution {
        public int[] findDiagonalOrder(int[][] mat) {
            int m = mat.length;
            int n = mat[0].length;
            int[] ans = new int[m * n];
            int k = 0;
            boolean upRight = true;
            int[][] delta = {{-1, 1}, {1, -1}};
            int i = 0, j = 0;
            while (i < m || j < n) {
                if (i >= 0 && i < m && j >= 0 && j < n) {
                    ans[k++] = mat[i][j];
                }
                if (upRight) {
                    i += delta[0][0];
                    j += delta[0][1];
                } else {
                    i += delta[1][0];
                    j += delta[1][1];
                }
                if (i < 0 || i >= m || j < 0 || j >= n) {
                    if (upRight) {
                        i = i + 1;
                    } else {
                        j = j + 1;
                    }
                    upRight = !upRight;
                }
            }
            return ans;
        }
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution().findDiagonalOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})));
        System.out.println(Arrays.toString(new Solution().findDiagonalOrder(new int[][]{{1, 2, 3}, {1, 2, 3}})));
    }
}
